package com.softlab.retailwholesalesystem.controller;

import com.softlab.retailwholesalesystem.entity.OrderGoodsMapEntity;
import com.softlab.retailwholesalesystem.service.IOrderGoodsMapService;
import com.softlab.retailwholesalesystem.service.exception.UpdateErrorException;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/map")
public class OrderGoodsMapController extends BaseController {

    @Autowired
    IOrderGoodsMapService service;

    @GetMapping("{id}")
    public JsonResult<List<OrderGoodsMapEntity>> getGoodsInOrder(@PathVariable Long id) {
        OrderGoodsMapEntity entity = new OrderGoodsMapEntity();
        entity.setOrderId(id);
        List<OrderGoodsMapEntity> list = service.getMap(entity);


        /*不该在这里出现，偷个懒*/
        for (OrderGoodsMapEntity e :
                list) {
            service.setSinglePriceByType(e);

        }
        list = service.getMap(entity);

        return new JsonResult<>(200, "查询订单详情成功", list);
    }

    @PostMapping
    public JsonResult<Void> addMap(@RequestBody OrderGoodsMapEntity map) {
        service.setSinglePriceByType(map);
        service.save(map);
        return new JsonResult<>(200, "记录添加成功");
    }

    @DeleteMapping("{id}")
    public JsonResult<Void> deleteMap(@PathVariable Long id) {
        OrderGoodsMapEntity entity = new OrderGoodsMapEntity();
        entity.setIsDelete(1);
        entity.setMapId(id);
        service.updateById(entity);
        return new JsonResult<>(200, "记录删除成功");
    }

    @PutMapping
    public JsonResult<Void> updateMap(@RequestBody OrderGoodsMapEntity map) {

        service.setSinglePriceByType(map);
        boolean b = service.updateById(map);
        if (b) {
            throw new UpdateErrorException("修改时遇到错误");
        }
        return new JsonResult<>(200, "修改成功");
    }

}
